//
//  ST_PecGroupCommentsCell.swift
//  btvideo
//
//  Created by mac on 2020/5/26.
//  Copyright © 2020 JarvanZhang. All rights reserved.
//

import UIKit
import SnapKit
import HandyJSON
import SwifterSwift

class ST_PecGroupCommentsCell: UITableViewCell {
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.selectionStyle = .none
        self.backgroundColor = .clear
        contentView.backgroundColor = UIColor.clear
        
        
        contentView.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 3, left: 0, bottom: 3, right: 0))
        }
        
        
        root_view.addSubview(commentsLabel)
        commentsLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(22)
        }
        
        contentView.addSubview(cellsView)
        cellsView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(commentsLabel.snp.bottom).offset(10)
            make.height.equalTo(180)
        }
        
        //        默认两个Cell 如需要 隐藏
        //
        let cell0 = CommentTableChildView()
        let cell1 = CommentTableChildView()
        
        cellsView.addSubview(cell0)
        cell0.snp.makeConstraints { (make) in
            make.left.top.right.equalToSuperview()
            make.height.equalTo(36+20)
        }
        
        cellsView.addSubview(cell1)
        cell1.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(cell0.snp.bottom)
            make.height.equalTo(36+20)
        }
        
        
        cellsView.subviews.forEach { (control) in
            
            let tap = UITapGestureRecognizer.init(target: self, action: #selector(reply_some_body_handle))
            control.isUserInteractionEnabled = true
            control.addGestureRecognizer(tap)
        }
        
        
        root_view.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(36)
            make.top.equalTo(cellsView.snp.bottom).offset(10)
            make.left.equalToSuperview().offset(15)
        }
        
        
        root_view.addSubview(inputBtn)
        
        inputBtn.snp.makeConstraints { (make) in
            
            make.centerY.equalTo(avatar_image_view)
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.right.equalToSuperview().offset(-74)
            make.height.equalTo(36)
            
        }
        
        
        root_view.addSubview(anonymity_label)
        anonymity_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalTo(inputBtn)
            make.height.equalTo(16)
        }
        
        root_view.addSubview(select_control)
        select_control.snp.makeConstraints { (make) in
            make.centerX.equalTo(anonymity_label)
            make.bottom.equalTo(anonymity_label.snp.top).offset(11/2.0)
        }
        
        
        root_view.addSubview(commentsNumberBtn)
        commentsNumberBtn.snp.makeConstraints { (make) in
            make.width.equalTo(141)
            make.height.equalTo(36)
            make.centerX.equalToSuperview()
            make.bottom.equalToSuperview().offset(-20)
        }
        
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //    MARK: - Properties
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = .white
        control.cornerRadius = 30
        return control
    }()
    
    
    fileprivate lazy var cellsView:UIView = {
        let control = UIView()
        return control
    }()
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 36/2.0
        return control
    }()
    
    
    fileprivate lazy var inputBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hex: 0xF5F8FA)
        control.cornerRadius = 36/2.0
        control.setTitleForAllStates("请输入评论")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 15, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(inputHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var select_control:UISwitch = {
        let control = UISwitch()
        control.onTintColor = UIColor.init(hex: 0xFEC207)
        control.tintColor = UIColor.init(hex: 0xACB4C0)
        control.backgroundColor = UIColor.init(hex: 0xACB4C0)
        control.layer.cornerRadius = 14
        control.isOn = ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark ?? false
        control.transform = CGAffineTransform(scaleX: 20/31.0, y: 20/31.0)
        control.addTarget(self, action: #selector(_switch_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    @objc fileprivate func _switch_handle(){
        
        
        if select_control.isOn{
            
            self.select_control.isOn = false
            
            let vc = BTVerticalAlertViewController.createAnonymousCommentAlert()
            
            vc.confirm_closure = {
                
                JVrequest(PH.setPrivacyValueApi,parameters: ["is_anonymous": "1"], success: { (json) in
                    
                    ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark = true
                    
                    self.select_control.isOn = true
                    
                    self.settingControlData()
                    
                }) { (code, err) in
                    
                    self.select_control.isOn = false
                    
                    self.parentViewController?.toast(text: err)
                    
                }
                
            }
            
            GlobalPresent(toController: vc)
            
        }else{
            
            JVrequest(PH.setPrivacyValueApi,parameters: ["is_anonymous": "2"], success: { (json) in
                
                ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark = false
                
                self.settingControlData()
                
            }) { (code, err) in
                
                self.select_control.isOn = true
                
                self.parentViewController?.toast(text: err)
                
            }
            
        }
        
        
    }
    
    fileprivate lazy var anonymity_label:UILabel = {
        let control = UILabel()
        control.text = "匿名评论"
        control.textColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.medium)
        return control
    }()
    
    fileprivate lazy var commentsNumberBtn:UIButton = {
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.cornerRadius = 36/2.0
        control.backgroundColor = Color.init(hex: 0xF2F4F7)
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        control.setTitleColorForAllStates(UIColor.init(hex: 0x333333)!)
        
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.semibold)
        
        control.addTarget(self, action: #selector(all_comments_click_handle), for: UIControl.Event.touchUpInside)
        
        return control
    }()
    
    
    
    fileprivate lazy var commentsLabel:UILabel = {
        let control = UILabel.init()
        control.text = "评论"
        control.textColor = Color.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    var beginInput:(()->())?
    
    var beginInputReplyClosure:((_ accid:String,_ commentId:Int,_ nickName:String)->())?
    
    @objc fileprivate func inputHandle(){
        
        beginInput?()
        
    }
    
    @objc fileprivate func reply_some_body_handle(gez:UITapGestureRecognizer){
        
        
        
        guard let v = gez.view,let idx = self.cellsView.subviews.firstIndex(of: v) else{
            return
        }
        
        
        
        guard let m = self.model.list[safe:Int(idx.uInt)] else{
            return
        }
        
        let nickname = m.nickname
        
        
        beginInputReplyClosure?(m.id.string,m.comment_id,nickname)
        
    }
    
    
    
    var allCommentsClickClosure:((ST_PecGroupCommentsCellModel)->())?
    
    @objc fileprivate func all_comments_click_handle(){
        
        
        self.parentViewController?.view.endEditing(true)
        
        self.allCommentsClickClosure?(self.model)
        
        
        
    }
    
    //    MARK: Bind Model
    fileprivate var lastIds:String?
    
    
    var onlyInputEmoji = false{
        didSet{
            if onlyInputEmoji{
                
                let str = FACE_AVATAE_STATE == 3 ? "该特质只支持emoji评论":"未真人认证只能使用emoji评论"
                inputBtn.setTitleForAllStates(str)
            }
        }
    }
    
    fileprivate func settingControlData(){
        
        if ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark == true{
            
            avatar_image_view.image = ST_ImageUtils.imageName("anonymous_small_icon")
            
            inputBtn.setTitleForAllStates("只有发布者本人能看到你的头像")
            
            return
        }
        
        inputBtn.setTitleForAllStates("请输入评论")
        
        if let url  = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.avatar.compress_small_image(width: 40*3).url{
            
            avatar_image_view.pin_setImage(from: url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        }
        
    }
    
    var model = ST_PecGroupCommentsCellModel(){
        didSet{
            
            let currentIds = model.list.map { (cellModel) -> String in
                return cellModel.id.string
            }.joined(separator: "+")
            
            if let last = lastIds,currentIds == last{
                return
            }
            
            lastIds = currentIds
            
            
            self.settingControlData()
            
            if let item = model.list.first{
                
                if let firstCell = self.cellsView.subviews.first as? CommentTableChildView{
                    
                    firstCell.model = item
                    
                    firstCell.snp.updateConstraints { (make) in
                        make.height.equalTo(item.cellHeight)
                    }
                }
            }
            
            if let item = model.list[safe:1]{
                
                if let secondCell = self.cellsView.subviews[safe:1] as? CommentTableChildView{
                    
                    secondCell.model = item
                    
                    secondCell.snp.updateConstraints { (make) in
                        make.height.equalTo(item.cellHeight)
                    }
                    
                    self.cellsView.subviews[safe:1]?.isHidden = false
                }
            }else{
                self.cellsView.subviews[safe:1]?.isHidden = true
            }
            
            self.cellsView.snp.updateConstraints { (make) in
                make.height.equalTo(model.cellsViewHeight)
            }
            
            self.commentsNumberBtn.isHidden = model.total < 2
            
            commentsNumberBtn.setTitleForAllStates("所有\(model.total)条评论")
        }
    }
    
}



//MARK: - Cell Model
class ST_PecGroupCommentsCellModel: NSObject,HandyJSON {
    
    var total = 0
    
    var list = Array<ST_CommentTableCellModel>()
    
    var cellsViewHeight = 0.cgFloat
    
    var cellHeight = 0.cgFloat
    
    //    bind Other Param
    var groupId = 0
    
    var userId = ""
    
    var peculiarity_id = ""
    
    /*1文字 2 表情*/
    var type = 1
    
    required override init() {
        super.init()
    }
    
    func setUpFrame(){
        
        list.forEach { (item) in
            item.ownUserId = self.userId
            item.setUpDataSet()
        }
        
        var h = 0.cgFloat
        
        if let item = list.first{
            
            h += item.cellHeight
        }
        
        if let item = list[safe:1]{
            
            h += item.cellHeight
            
        }
        
        cellsViewHeight = h
        
        cellHeight = cellsViewHeight + 52 + 37 + 10 + 76 + 1
        
        if list.count < 2{
            
            cellHeight -= 56
        }
    }
    
}



//MARK: - PlaceHolder Cell

class PecGroupCommentsPlaceHolderCell: UITableViewCell {
    
    
    override init(style: UITableViewCell.CellStyle, reuseIdentifier: String?) {
        super.init(style: style, reuseIdentifier: reuseIdentifier)
        
        self.selectionStyle = .none
        self.backgroundColor = .clear
        contentView.backgroundColor = UIColor.clear
        
        contentView.addSubview(root_view)
        root_view.snp.makeConstraints { (make) in
            make.edges.equalToSuperview().inset(UIEdgeInsets.init(top: 3, left: 0, bottom: 3, right: 0))
        }
        
        root_view.addSubview(avatar_image_view)
        avatar_image_view.snp.makeConstraints { (make) in
            make.width.height.equalTo(36)
            make.bottom.equalToSuperview().offset(-20)
            make.left.equalToSuperview().offset(15)
        }
        
        
        root_view.addSubview(inputBtn)
        
        inputBtn.snp.makeConstraints { (make) in
            
            make.centerY.equalTo(avatar_image_view)
            make.left.equalTo(avatar_image_view.snp.right).offset(10)
            make.right.equalToSuperview().offset(-74)
            make.height.equalTo(36)
            
        }
        
        
        
        root_view.addSubview(anonymity_label)
        anonymity_label.snp.makeConstraints { (make) in
            make.right.equalToSuperview().offset(-15)
            make.bottom.equalTo(inputBtn)
            make.height.equalTo(16)
        }
        
        root_view.addSubview(select_control)
        select_control.snp.makeConstraints { (make) in
            make.centerX.equalTo(anonymity_label)
            make.bottom.equalTo(anonymity_label.snp.top).offset(11/2.0)
        }

        
        
        root_view.addSubview(content_label)
        content_label.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.right.equalToSuperview().offset(-15)
            make.height.equalTo(20)
            make.bottom.equalTo(inputBtn.snp.top).offset(-20)
        }
        
        root_view.addSubview(commentsLabel)
        commentsLabel.snp.makeConstraints { (make) in
            make.left.equalToSuperview().offset(15)
            make.top.equalToSuperview().offset(20)
            make.height.equalTo(22)
        }
        
        settingControlData()
        
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    //    MARK: - Properties
    fileprivate lazy var root_view:UIView = {
        let control = UIView()
        control.backgroundColor = .white
        control.cornerRadius = 30
        return control
    }()
    
    fileprivate lazy var avatar_image_view:UIImageView = {
        let control = UIImageView()
        control.contentMode = .scaleAspectFill
        control.cornerRadius = 36/2.0
        return control
    }()
    
    
    fileprivate lazy var inputBtn:UIButton = {
        
        let control = UIButton.init(type: UIButton.ButtonType.custom)
        control.backgroundColor = Color.init(hex: 0xF5F8FA)
        control.cornerRadius = 36/2.0
        control.setTitleForAllStates("请输入评论")
        control.titleLabel?.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        control.titleEdgeInsets = UIEdgeInsets.init(top: 0, left: 15, bottom: 0, right: 0)
        control.contentHorizontalAlignment = .left
        control.setTitleColor(UIColor.init(hex: 0xACB4C0)!, for: UIControl.State.normal)
        control.addTarget(self, action: #selector(inputHandle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    
    fileprivate lazy var select_control:UISwitch = {
        let control = UISwitch()
        control.onTintColor = UIColor.init(hex: 0xFEC207)
        control.tintColor = UIColor.init(hex: 0xACB4C0)
        control.backgroundColor = UIColor.init(hex: 0xACB4C0)
        control.layer.cornerRadius = 14
        control.isOn = ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark ?? false
        control.transform = CGAffineTransform(scaleX: 20/31.0, y: 20/31.0)
        control.addTarget(self, action: #selector(_switch_handle), for: UIControl.Event.touchUpInside)
        return control
    }()
    
    fileprivate lazy var anonymity_label:UILabel = {
        let control = UILabel()
        control.text = "匿名评论"
        control.textColor = UIColor.init(hex: 0x333333)
        control.font = UIFont.systemFont(ofSize: 11, weight: UIFont.Weight.medium)
        return control
    }()
    
    
    fileprivate lazy var content_label:UILabel = {
        let control = UILabel.init()
        control.textColor = Color.init(hexString: "#61666F")
        control.font = UIFont.systemFont(ofSize: 14, weight: UIFont.Weight.regular)
        return control
    }()
    
    fileprivate lazy var commentsLabel:UILabel = {
        let control = UILabel.init()
        control.text = "评论"
        control.textColor = Color.init(hexString: "#333333")
        control.font = UIFont.systemFont(ofSize: 16, weight: UIFont.Weight.semibold)
        return control
    }()
    
    var beginInput:(()->())?
    
    @objc fileprivate func inputHandle(){
        
        beginInput?()
        
    }
    
    @objc fileprivate func _switch_handle(){
        
        
        if select_control.isOn{
            
            self.select_control.isOn = false
            
            let vc = BTVerticalAlertViewController.createAnonymousCommentAlert()
            
            vc.confirm_closure = {
                
                JVrequest(PH.setPrivacyValueApi,parameters: ["is_anonymous": "1"], success: { (json) in
                    
                    ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark = true
                    
                    self.select_control.isOn = true
                    
                    self.settingControlData()
                    
                }) { (code, err) in
                    
                    self.select_control.isOn = false
                    
                    self.parentViewController?.toast(text: err)
                    
                }
                
            }
            
            GlobalPresent(toController: vc)
            
        }else{
            
            JVrequest(PH.setPrivacyValueApi,parameters: ["is_anonymous": "2"], success: { (json) in
                
                ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark = false
                
                self.settingControlData()
                
            }) { (code, err) in
                
                self.select_control.isOn = true
                
                self.parentViewController?.toast(text: err)
                
            }
            
        }
        
        
    }
    
    fileprivate func settingControlData()  {
        
        //
        if ST_BTUserInfoManager.shared.additional_attributes?.anonymousRemark == true{
            
            avatar_image_view.image = ST_ImageUtils.imageName("anonymous_small_icon")
            
            inputBtn.setTitleForAllStates("只有发布者本人能看到你的头像")
            
            return
        }
        
        inputBtn.setTitleForAllStates("请输入评论")
        
        if let url  = ST_BTUserInfoManager.shared.current_account_info?.userinfo?.avatar.compress_small_image(width: 40*3).url{
            
            avatar_image_view.pin_setImage(from: url, placeholderImage: ST_SwiftConst.shared.fetch_random_place_holder_image())
        }
    }
    
    
    func tipsText(nickName:String)  {
        content_label.text = "喜欢这个特质吗？评论让 \(nickName) 知道吧！"
    }
    
    var onlyInputEmoji = false{
        didSet{
            
            var str = "请输入评论"
            if FACE_AVATAE_STATE != 3{
                str = "未真人认证只能使用emoji评论"
            }else if onlyInputEmoji{
                str = "该特质只支持emoji评论"
            }
            
            inputBtn.setTitleForAllStates(str)
        }
    }
    
}
